package com.banshuibao.bsb_android.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.FindPasswordModel;
import com.banshuibao.bsb_android.model.SendSmsModel;
import com.banshuibao.bsb_android.util.MD5;
import com.banshuibao.bsb_android.util.XToast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FindPasswordActivity extends BaseActivity implements View.OnClickListener {

    private EditText phoneNumber, mYan, mPasswordOne, mPasswordTwo;
    private Button mbtn, mCommit;
    private String smsMessageSid;
    private int isSelected = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_password);
        initView();
    }

    //获取验证码倒计时
    CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mbtn.setText(millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            mbtn.setEnabled(true);
            mbtn.setText("重新获取");
            mbtn.setTextSize(14);
        }
    };

    private void initView() {
        setTitleText("忘记密码");
        phoneNumber = findViewById(R.id.register_phoneNumber);
        mYan = findViewById(R.id.register_yanzhengma);
        mPasswordOne = findViewById(R.id.password_one);
        mPasswordTwo = findViewById(R.id.password_two);
        mbtn = findViewById(R.id.register_huoqu_btn);
        mCommit = findViewById(R.id.commit);
        mbtn.setOnClickListener(this);
        mCommit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_huoqu_btn:
                String phoneNumber1 = phoneNumber.getText().toString().trim();
                if (isMatchMobilLength(phoneNumber1, 11) && isMobilNo(phoneNumber1)) {
                    setpost(phoneNumber1);
                } else {
                    XToast.showToast(this, "输入电话号码有误");
                }
                break;
            case R.id.commit:
                String s1 = phoneNumber.getText().toString().trim();
                String s2 = mYan.getText().toString().trim();
                String s3 = mPasswordOne.getText().toString().trim();
                String s4 = mPasswordTwo.getText().toString().trim();
                if (TextUtils.isEmpty(s1)) {
                    XToast.showToast(this,"请输入您的手机号");
                    return;
                }
                if (!isMatchMobilLength(s1, 11) && !isMobilNo(s1)) {
                    XToast.showToast(this,"您的手机号输入有误");
                    return;
                }
                if (isSelected != 2){
                    XToast.showToast(this,"请获取验证码");
                    return;
                }
                if (TextUtils.isEmpty(s2)) {
                    XToast.showToast(this,"请输入验证码");
                    return;
                }
                if (TextUtils.isEmpty(s3)) {
                    XToast.showToast(this,"请输入新密码");
                    return;
                }
                if (!isPassword(s3)) {
                    XToast.showToast(this,"请输入正确的密码格式");
                    return;
                }
                if (TextUtils.isEmpty(s4)) {
                    XToast.showToast(this,"请确认新密码");
                    return;
                }
                try {
                    findPost(s1,s2,s3,s4);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    //获取验证码接口
    private void setpost(String phoneNumber) {
        SendSmsModel.body body = new SendSmsModel.body();
        body.setPhone(phoneNumber);
        body.setSendtype("UF");
        HttpUtil.doPost(Constants.Url.SEND_SMS, body, new HttpResponse(this, SendSmsModel.class) {
            @Override
            public void onResult(Object obj) {
                isSelected = 2;
                timer.start();
                SendSmsModel sendSmsModel = (SendSmsModel) obj;
                smsMessageSid = sendSmsModel.getSmsMessageSid();
            }
        });
    }

    //找回密码接口
    private void findPost(String s1, String s2, String s3, String s4) throws Exception {
        FindPasswordModel.body body = new FindPasswordModel.body();
        body.setPhone(s1);
        body.setSmsCode(s2);
        body.setPwd(MD5.encryptMD5ToString(s3.getBytes()));
        body.setNewPwd(MD5.encryptMD5ToString(s4.getBytes()));
        if (TextUtils.isEmpty(smsMessageSid)){
            return;
        }
        body.setSmsMessageSid(smsMessageSid);
        HttpUtil.doPost(Constants.Url.FIND_PWD, body, new HttpResponse(this) {
            @Override
            public void onResult(Object obj) {
                XToast.showToast(FindPasswordActivity.this,"密码修改成功,请重新登录");
                finish();
            }
        });
    }

    public boolean isMatchMobilLength(String phone, int length) {
        if (!TextUtils.isEmpty(phone)) {
            return phone.length() == length;
        }
        return false;
    }

    public boolean isPassword(String phone) {
        Pattern pattern = Pattern.compile("[0-9a-zA-Z\\d]{6,15}");
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    public boolean isMobilNo(String phone) {
        String repexp = "^[1][34578]\\d{9}";
        Pattern pattern = Pattern.compile(repexp);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    //取消
    @Override
    protected void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }

    //点击隐藏输入框之外 隐藏输入框
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
